package cn.ubest.mvvmcore

import android.app.Activity
import android.app.Application
import android.app.Application.ActivityLifecycleCallbacks
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Process
import cn.ubest.mvvmcore.utils.ActivityManager
import cn.ubest.mvvmcore.widget.CustomRefreshHeader
import com.facebook.stetho.Stetho
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import org.litepal.LitePal

/**
 * Created by maoqi on 2020/9/24.
 */
open class BaseApplication : Application(), ActivityLifecycleCallbacks {

    companion object {
        lateinit var application: Application
        lateinit var handler: Handler
        var mainThreadId: Int = -1

        init {
            SmartRefreshLayout.setDefaultRefreshHeaderCreator { context, layout ->
                CustomRefreshHeader(context)
            }
            //线程捕获异常
//            Thread.setDefaultUncaughtExceptionHandler { t: Thread, e: Throwable ->
//                //handle exception here
//                LogUtils.d("Thread '${t.name}' throws an exception with message '${e.message}'")
//            }
        }
    }

    override fun onCreate() {
        super.onCreate()
        application = this
        //初始化Stetho
        //初始化Stetho
        if (BuildConfig.DEBUG) {
            //测试环境初始化Stetho
            Stetho.initializeWithDefaults(this)
        }
        registerActivityLifecycleCallbacks(this)
        LitePal.initialize(this)
        handler = Handler(Looper.getMainLooper())
        mainThreadId = Process.myTid()
    }

    override fun onActivityPaused(p0: Activity) {

    }

    override fun onActivityStarted(p0: Activity) {
    }

    override fun onActivityDestroyed(p0: Activity) {
        ActivityManager.getInstance().removeActivity(p0)
    }

    override fun onActivitySaveInstanceState(p0: Activity, p1: Bundle) {
    }

    override fun onActivityStopped(p0: Activity) {
    }

    override fun onActivityCreated(p0: Activity, p1: Bundle?) {
        ActivityManager.getInstance().addActivity(p0)
    }

    override fun onActivityResumed(p0: Activity) {
    }
}